﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Compilex.Automata;
using Compilex.BaseLibrary;

namespace Infraestruturex.Automata.SPA
{
    [Serializable]
    public class SPAState
    {
        public string Name { get; set; }
        public bool IsAcceptState { get; set; }

        public bool IsSubmachineCallState { get; set; }
        public SPA SubmachineToCall { get; set; }
        public SPAState SubmachineCallReturnState { get; set; }
        public string SubmachineCallSemanticActionName { get; set; }

        public SimpleList<SimpleTransitionRuleWithSemanticAction> Transitions { get; set; }

        public SPAState(string name)
        {
            this.Name = name;
            this.IsAcceptState = false;
            this.Transitions = new SimpleList<SimpleTransitionRuleWithSemanticAction>();
        }
        public SPAState(string name, bool isFinal)
        {
            this.Name = name;
            this.IsAcceptState = isFinal;
            this.Transitions = new SimpleList<SimpleTransitionRuleWithSemanticAction>();
        }

        public void AddTransition(string input, SPAState destination)
        {
            Transitions.Add(new SimpleTransitionRuleWithSemanticAction(input, destination));
        }

        public void AddTransition(string input, SPAState destination, string semanticActionName)
        {
            Transitions.Add(new SimpleTransitionRuleWithSemanticAction(input, destination, semanticActionName));
        }

        public SPAState TryGetDestinationState(string input)
        {
            ITransitionRule<SPAState> transition = TryGetTransition(input);
            if (transition != null)
            {
                return transition.Destination;
            }
            else
            {
                return null;
            }
        }

        public SimpleTransitionRuleWithSemanticAction TryGetTransition(string input)
        {
            SimpleTransitionRuleWithSemanticAction transition = Transitions.ToArray().Where(t => t.MatchesInput(input)).FirstOrDefault();
            return transition;
        }

        public string TryGetSemanticActionName(string input)
        {
            SimpleTransitionRuleWithSemanticAction transition = TryGetTransition(input);
            if (transition != null)
            {
                return transition.SemanticActionName;
            }
            else
            {
                return null;
            }
        }

        public override string ToString()
        {
            return this.Name;
        }

    }
}
